<template>
  <div class="top">
    <el-tabs type="card" v-model="active" @tab-click="changeActive">
      <el-tab-pane label="销售中" name="0"></el-tab-pane>
      <el-tab-pane label="已下架" name="1"></el-tab-pane>
    </el-tabs>

    <el-row class="fitersLine">
      <el-col :span="24">
        <el-form :inline="true">
          {{getGradesList}}{{getSubjectsList}}
          <el-form-item label="年级">
            <el-select v-model="initPostData.gradeId" placeholder="请选择">
              <el-option label="全部" value=""></el-option>
              <el-option v-for="item in gradeList" :key="item.id" :label="item.gradeName" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="科目">
            <el-select v-model="initPostData.subjectId" placeholder="请选择">
              <el-option label="全部" value=""></el-option>
              <el-option v-for="item in subjectList" :key="item.id" :label="item.subjectName" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="类型">
            <el-select v-model="initPostData.commodityType" placeholder="请选择">
              <el-option label="全部" value=""></el-option>
              <el-option v-for="item in typeList" :key="item.id" :label="item.typeName" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="推荐类型">
            <el-select v-model="initPostData.sign" placeholder="请选择">
              <el-option label="--" :value="null"></el-option>
              <el-option v-for="item in signList" :key="item.id" :label="item.typeName" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否为广告课程">
            <el-select v-model="initPostData.isAd" placeholder="请选择" clearable>
              <el-option v-for="ad in isAdList" :key="ad.id" :label="ad.name" :value="ad.type">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="课程主题类型">
            <el-select v-model="initPostData.topicId" placeholder="请选择" clearable>
              <el-option v-for="ad in topicList" :key="ad.id" :label="ad.name" :value="ad.id">
              </el-option>
            </el-select>
          </el-form-item>   
          <!-- 是否为vip商品 -->
          <el-form-item label="是否为vip商品">
            <el-select v-model="initPostData.isVip" placeholder="请选择" clearable>
              <el-option v-for="vip in isVipList" :key="vip.id" :label="vip.name" :value="vip.type">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="ID">
            <el-input v-model="initPostData.commodityId" placeholder="请输入商品ID"></el-input>
          </el-form-item>
          <el-form-item label="商品名称">
            <el-input v-model="initPostData.commodityName" placeholder="请输入商品名称"></el-input>
          </el-form-item>
          <el-form-item label="专家名称">
            <el-input v-model="initPostData.professorName" placeholder="请输入专家名称"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getDataByFilter">查询</el-button>
            <el-button v-if='active == "1"' type="danger" @click='operateGood(2)'>批量删除</el-button>
            <el-button type="primary" @click='operateGood(active)'>批量{{operateText[active]}}</el-button>
          </el-form-item>
          <router-link :to="{path: 'create'}">
            <el-button type="success">发布商品</el-button>
          </router-link>
        </el-form>
      </el-col>
    </el-row>

    <el-table ref="multipleTable" :key='tableKey' :data="list" :default-sort="{prop: 'inTime', order: 'descending'}" style="width: 100%" @selection-change="getSelectedGoods" @sort-change="getSortGoods" v-loading="listLoading" element-loading-text="数据加载中，请稍后" border fit highlight-current-row>
      <el-table-column type="selection" align="center" min-width="30"></el-table-column>
      <el-table-column align="center" prop="id" label="ID" min-width="30"></el-table-column>
      <el-table-column label="商品图片" align="center" min-width="160">
        <template slot-scope="scope">
          <img :src="scope.row.picList[0]" :alt="scope.row.commodityName" width="136" height="80">
        </template>
      </el-table-column>
      <el-table-column align="center" prop="viewCount" label="浏览数" min-width="60"
      sortable="custom"></el-table-column>
      <el-table-column align="center" prop="useNum" label="有用数" min-width="60"
      sortable="custom"></el-table-column>
      <el-table-column align="center" prop="commodityName" label="商品名称" min-width="120"></el-table-column>
      <el-table-column align="center" prop="sign" label="推荐类型" min-width="80">
        <template slot-scope="scope"> {{scope.row.sign == '新' ? '新课' : scope.row.sign == '热' ? '火爆' : scope.row.sign == '荐' ? '推荐' : '--' }} </template>
      </el-table-column>
      <el-table-column align="center" prop="isAd" label="是否为广告课程" min-width="100">
        <template slot-scope="scope"> {{scope.row.isAd ? '是' : '否' }} </template>
      </el-table-column>
      <!-- 是否为vip商品 -->
      <el-table-column align="center" prop="isVip" label="是否为vip商品" min-width="100">
        <template slot-scope="scope"> {{scope.row.isVip ? '是' : '否' }} </template>
      </el-table-column>
      <!-- 专家名称 -->
      <el-table-column align="center" prop="professorName" label="专家名称" min-width="80">
        <template slot-scope="scope"> {{scope.row.professorName || '--'}} </template>
      </el-table-column>
      <el-table-column align="center" prop="gradeName" label="年级" min-width="60">
        <template slot-scope="scope"> {{scope.row.gradeName || '--'}} </template>
      </el-table-column>
      <el-table-column align="center" prop="subjectName" label="科目" min-width="60">
        <template slot-scope="scope"> {{scope.row.subjectName || '--'}} </template>
      </el-table-column>
      <el-table-column align="center" prop="topicName" :label="changeTopicLabel[active]" min-width="100">
        <template slot-scope="scope"> {{scope.row.topicName || '--'}} </template>
      </el-table-column>
      <el-table-column align="center" prop="inTime" label="创建时间" min-width="100" sortable="custom">
        <template slot-scope="scope">{{scope.row.inTime|dateformat('YYYY-MM-DD HH:mm')}} </template>
      </el-table-column>
      <el-table-column align="center" prop="weights" label="权重" min-width="50" sortable="custom"></el-table-column>
      <el-table-column align="center" prop="commodityTypeDesc" label="类型" min-width="50"></el-table-column>
      <el-table-column align="center" prop="name" label="操作" show-overflow-tooltip min-width="140">
        <template slot-scope="scope">
          {{operateGoods}}
          <el-button size="mini" @click="editGood(scope.row.id)">编辑</el-button>
          <el-button size="mini" type="primary" @click="operateGood(active,scope.row.id)">{{operateText[active]}}</el-button>
          <el-button v-if='active == "1"' size="mini" type="danger" @click="operateGood('2',scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog v-if='typeDialogVisible' title="编辑商品" width="60%" top="4vh" :visible.sync="typeDialogVisible" :before-close="handleClose">
      <commondity-create v-on:edit-complete='editCompleted' :commodity-id='toBeEditedCommodityId'></commondity-create>
    </el-dialog>

    <el-row type="flex" justify="space-between" style="padding-top:20px">
      <el-col style="text-align:right">
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="initPostData.pageNo" :page-sizes="[10, 20, 30, 50]" :page-size="10" layout="total, sizes, prev, pager, next" :total="total">
        </el-pagination>
      </el-col>
    </el-row>
  </div>
</template>


<script>

import commondityCreate from './create'
import { getToken } from '@/utils/auth' // 验权
import { getGoodsList, operateGood } from '@/api/goods'
import { getGradeList } from '@/api/grade'
import { getSubjectList } from '@/api/subject'
export default {
  name: 'articleDetail',
  components: { commondityCreate },
  data() {
    return {
      headers: {},
      tableKey: 0,
      editWeights: 0,
      total: null,
      list: null,
      listLoading: true,
      typeDialogVisible: false,
      active: '0', //"0"：当前处于上架  "1"：当前展示下架   (ELE UI required string)
      changeTopicLabel: ['课程主题', '推荐主题'],
      gradeList: [],
      subjectList: [],
      typeList:[
        { id:1, typeName:'视频' },
        { id:2, typeName:'图文' },
        { id:3, typeName:'语音' }
      ],
      topicList:[
        {id:1,name:"大学报考"},
        {id:2,name:"学习提分"},
        {id:3,name:"心理辅导"},
        {id:4,name:"生涯规划"},
        {id:5,name:"精品课程"},
        {id:6,name:"测试"},
        {id:7,name:"1+5+5课程"}
      ],
      signList: [{
        id: '新',
        typeName: '新课'
      }, {
        id: '荐',
        typeName: '推荐'
      }, {
        id: '热',
        typeName: '火爆'
      }],
      isAdList: [{
        id: 1,
        name: '是',
        type: 1
      }, {
        id: 2,
        name: '否',
        type: 0
      }],
      isVipList: [{
        id: 1,
        name: '是',
        type: 1
      }, {
        id: 2,
        name: '否',
        type: 0
      }],
      initPostData: {
        commodityName: '',
        professorName: null,
        commodityStatus: 0, // 0：上架1：下架
        gradeId: null, // 年级
        pageNo: 1,
        pageSize: 10,
        sortField: null, // weights:权重排序 inTime:日期排序
        sortWay: null, // desc降序, asc 升序
        commodityId:null,
        subjectId: null, // 科目
        topicId: null,
        commodityType: null, // 新增的商品类型
        isAd: null, // 是否为广告课程
        isVip: null, // 是否为vip课程
        sign: null // 推荐类型
      },
      operateParams: {
        ids: [],
        operateType: ''
      },
      batchGoods: [],
      operateText: ['下架', '上架', '删除'],
      toBeEditedCommodityId: ''

    }
  },
  created() {
    this.headers = { accessToken: getToken() }
    this.getGoodsData()
  },
  methods: {
    handleClose() {
      this.$confirm('数据未保存，确认关闭？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.typeDialogVisible = false
      }).catch(() => {})
    },
    getSortGoods(filed){
      const { prop, order } = filed
      const { initPostData } = this
      initPostData['sortField'] = prop
      if(prop){
        initPostData['sortWay'] = order == 'descending' ? 'DESC' : 'ASC'
      }else{
        initPostData['sortWay'] = null
      }
      this.initPostData = initPostData
      this.getGoodsData()
    },
    dealDataForGetList() {
      this.listLoading = true
      const params = this.initPostData
      const { dateformat } = this
      if (dateformat) {
        params.startDate = dateformat[0]
        params.endDate = dateformat[1]
      } else {
        delete params.beginTime
        delete params.endTime
      }
      return params
    },
    getGoodsData() {
      this.initPostData.commodityStatus = JSON.parse(this.active)
      getGoodsList(this.initPostData).then(response => {
        console.log(response)
        const { code, data: { total, data, list } = { total: 0, data: [] } } = response
        if (code == 0) {
          this.total = total
          this.list = data || list
          this.listLoading = false
          if (total == 0) {
            this.$message({
              message: '未找到符合条件的课程！',
              type: 'warning'
            })
          }
        }
      }).catch(reject => {
        this.listLoading = false
      })
    },
    changeActive(tab, event) {
      this.getGoodsData()
    },
    getDataByFilter() {
      this.initPostData.pageNo = 1
      this.getGoodsData()
    },
    editGood(id) {
      this.typeDialogVisible = true
      this.toBeEditedCommodityId = id
    },
    editCompleted(state) {
      this.typeDialogVisible = false
      if (state) {
        this.getGoodsData()
      }
    },
    checkOperateParams(type, id) {
      if (!id && this.batchGoods.length == 0) {
        this.$message({
          message: '请选择您要' + this.operateText[type] + '的商品！',
          type: 'warning'
        })
        return false
      }
      return true
    },
    operateGood(type, id) {
      if (!this.checkOperateParams(type, id)) { return false }
      const batchText = id ? '' : '选中的'
      this.$confirm('确定' + this.operateText[type] + '当前' + batchText + '商品吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.operateParams.operateType = 1 * type
        this.operateParams.ids = id ? [id] : [...this.batchGoods]
        id || (this.batchGoods = [])
      }).catch(reject => {
        this.operateParams.operateType = ''
        this.operateParams.ids = []
      })
    },
    getSelectedGoods(goods) {
      this.batchGoods = Array.from(goods, good => good.id)
    },
    dealGoodsBatch(status) {
      const type = 1 * status
      this.$confirm('确定' + this.operateText[type] + '当前选中的商品吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.operateParams.operateType = 2
        this.operateParams.ids = [...this.batchGoods]
      }).catch(reject => {
        this.operateParams.operateType = ''
        this.operateParams.ids = []
      })
    },
    changeWeights(row) {
    },
    formateNumber(value) {
    },
    handleSizeChange(val) {
      this.initPostData.pageSize = val
      this.getGoodsData()
    },
    handleCurrentChange(val) {
      this.initPostData.pageNo = val
      this.getGoodsData()
    }
  },
  computed: {
    operateGoods() {
      const type = this.operateParams.operateType
      if (type === '') { return '' }
      this.listLoading = true
      operateGood(this.operateParams).then(response => {
        this.listLoading = false
        const { code } = response
        if (code == 0) {
          this.$message({
            message: this.operateText[type] + '成功！',
            type: 'success'
          })
          this.operateParams.operateType = ''
          this.operateParams.ids = []
          this.getGoodsData()
        }
      }).catch(reject => {
        this.listLoading = false
      })
      return ''
    },
    getGradesList() {
      getGradeList().then(res => {
        const { code, data } = res
        if (code == 0) { this.gradeList = data }
      })
    },
    getSubjectsList() {
      getSubjectList().then(res => {
        const { code, data } = res
        if (code == 0) { this.subjectList = data }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.top {
  padding: 10px;
}
</style>
<style rel="stylesheet/scss" lang="scss">
.el-upload {
  text-align: left;
}
.el-dialog__body {
  line-height: 0;
  padding: 0 0 20px;
}
.el-dialog__header {
  padding-bottom: 0;
}
.el-steps--simple {
  margin: 10px 0;
}
.border-none {
  input {
    border: none;
    padding: 0;
    text-align: center;
    &:focus {
      border: 1px solid #dcdfe6;
    }
  }
}
.el-table--enable-row-hover {
  .el-table__body {
    tr:hover > td {
      background: transparent;
    }
  }
}
.fitersLine {
  .el-form-item__content {
    margin-left: 0 !important;
  }
  .el-form-item__label {
    min-width: auto !important;
  }
}
.el-table .cell {
  line-height: 1;
  padding: 0 3px;
}
</style>